package org.yufan.rpc.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yufan.bean.Item;
import org.yufan.bean.ItemDesc;
import org.yufan.result.Result;
import org.yufan.rpc.service.ItemDescService;
import org.yufan.rpc.service.ItemService;
import org.yufan.utils.HttpClientUtil;
import org.yufan.utils.JsonUtils;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;

@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService {

    @Autowired
    private JmsTemplate jmsTemplate;

    private Logger LOGGER=LoggerFactory.getLogger(ItemServiceImpl.class);
    @Autowired
    private ItemDescService itemDescService;

    @Override
    public void itemAdd(Item item, String desc) {

        item.setStatus(Item.STATUS_DOWN);
        item.setUpdated(new Date());
        item.setCreated(item.getUpdated());
        this.save(item);
        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId( item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(item.getUpdated());
        itemDesc.setCreated(item.getUpdated());
        itemDescService.save(itemDesc);

    }

    @Override
    public void updateItem(Item item, String desc) {



        if(item==null||StringUtils.isEmpty(desc)){
            return;
        }
        //设置修改时间
        item.setUpdated(new Date());
        this.update(item);

        //修改商品描述
        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(item.getUpdated());
        itemDescService.update(itemDesc);

        //TODO
        //通知前台系统删除缓存
//        String json = HttpClientUtil.doPost("http://localhost:8080/item/cache/" + item.getId());
//        Result result = JsonUtils.jsonToPojo(json, Result.class);
//        if(result.getStatus().equals("success")){
//            //成功
//            LOGGER.debug("通知删除缓存成功!,商品id为{}",item.getId());
//        }

        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                LOGGER.info("admin发送消息，商品id为{}",item.getId());
                return session.createTextMessage(item.getId()+"");
            }
        });


    }
}
